#include <windows.h>
#include <shlwapi.h>
#include "Setting.h"
#include "Language.h"

CLanguage* CLanguage::m_instance = NULL;
static const tstring APP         = _T("lang");


CLanguage::CLanguage(void) {
	CSetting *pSetting = CSetting::getInstance();
	// 1. if setting has...
	// loadLanguage(pSetting->getValue("lang"));

	// 2. get system language
	LCID lcid = GetSystemDefaultLCID();
	char code[10];
	sprintf_s(code, 10, "%04x", (lcid & 0xffff)); // use it 0-15 bits
	std::string lang = code;
	loadLanguage(lang);
}

CLanguage::~CLanguage(void) {
}

/**
 * @param lang:
 *		- 0409		English
 *		- 0804		Simplified Chinese
 *		- 0404		Traditional Chinese
 *		- etc...
 */
bool CLanguage::loadLanguage(const std::string &lang) {
	TCHAR tLang[256];
	memset (tLang, 0, sizeof(tLang));
#ifdef UNICODE
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, lang.c_str(), lang.length(), tLang, 256);
#else
	strcpy_s(tLang, 256, lang);
#endif

	tstring tlang = tLang;

	tstring defLang = _T("0409");
	tstring prefix = _T("lang-");
	tstring ext = _T(".ini");
	// tstring file = prefix + tlang + ext;

	TCHAR buf[MAX_PATH];
	GetModuleFileName(NULL, buf, MAX_PATH);
	tstring file = buf;
	size_t offset = file.find_last_of('\\');
	ATLASSERT (offset != tstring::npos);
	file = file.substr(0, offset + 1);
	file += prefix + tlang + ext;


	if (file == m_iniFile) {
		return true;
	}

	if (!PathFileExists(file.c_str())) {
		file = buf;
		size_t offset = file.find_last_of('\\');
		ATLASSERT (offset != tstring::npos);
		file = file.substr(0, offset + 1);
		file += prefix + defLang + ext;
		if (file == m_iniFile) {
			return true;
		}

		if (!PathFileExists(file.c_str())) {
			assert (false);
			return false; // not exists
		} else {
			m_iniFile = file;
		}
	} else {
		m_iniFile = file;
	}

	m_cache.erase(m_cache.begin(), m_cache.end());

	return true;
}


CLanguage* CLanguage::getInstance() {
	if (m_instance == NULL) {
		m_instance = new CLanguage();
	}

	return m_instance;
}

tstring CLanguage::getString(const tstring& key) {
	if (m_cache.find(key) != m_cache.end()) {
		return m_cache[key];
	}

	TCHAR buf[256];
	if (m_iniFile.length() > 0) {
		if (GetPrivateProfileString(APP.c_str(), key.c_str(), NULL, buf, 256, m_iniFile.c_str()) > 0) {
			tstring value = buf;
			m_cache[key] = value;
			return value;
		}
	}

	// ATLTRACE (_T("Language: (%s) not found\n"), key.c_str());
	return key;
}




